/**
 * FileName: PurchaseController
 * Author:   Molzx
 * Date:     2019/10/3 18:34
 * Description: 采购申请单控制器
 */
package com.dgut.Controller;

import com.alibaba.fastjson.JSONObject;
import com.dgut.Service.IPurchaseRcdService;
import com.dgut.Service.IPurchaseService;
import com.dgut.domain.Purchase;
import com.dgut.domain.PurchaseQuery;
import com.dgut.domain.PurchaseRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;


/**
 * 〈采购申请单控制器，
 * 负责采购申请的创建，审核，修改，删除，
 * 采购申请单的审批记录，添加，展示
 * 〉
 */
@Controller
public class PurchaseController {

    //采购申请单的Service
    @Autowired
    private IPurchaseService purchaseService;

    //采购申请单审批记录的Service
    @Autowired
    private IPurchaseRcdService purchaseRcdService;


    /**
     * 采购申请添加操作
     *
     * @param purchase
     * @return
     */
    @CrossOrigin
    @RequestMapping(value = "/Purchase/add", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String addPurchase(@RequestBody Purchase purchase) {
        System.out.println(purchase.toString());
        // 将获取的json数据封装一层，然后在给返回
        JSONObject result = new JSONObject();
        String status = "ERROR";
        String msg = "操作失败";
        try {
            //插入操作
            int c1 = purchaseService.savePurchase(purchase);

            //采购申请创建，审批记录插入数据库
            PurchaseRecord record = setPRecord(purchase, "创建");
            int c2 = purchaseRcdService.savePurchaseRecord(record);

            if (c1 + c2 == 2) {
                status = "OK";
                msg = "操作成功";
                //return result.toJSONString();
            }
        } catch (Exception e) {
            msg = e.getMessage();
            System.out.println(e.getMessage());
        } finally {
            result.put("STATUS", status);
            result.put("msg", msg);
            return result.toJSONString();
        }
    }

    /**
     * 采购申请删除
     *
     * @param request
     * @return
     */
    @CrossOrigin
    @RequestMapping(value = "/Purchase/delete", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String deletePurchase(@RequestBody JSONObject request) {
        String id = request.getString("purchapplyid");
        // 将获取的json数据封装一层，然后在给返回
        JSONObject result = new JSONObject();
        String status = "ERROR";
        String msg = "操作失败";
        try {
            //删除操作
            if (purchaseService.deletePurchase(id) == 2) {
                status = "OK";
                msg = "操作成功";
                //return result.toJSONString();
            }
        } catch (Exception e) {
            msg = e.getMessage();
            System.out.println(e.getMessage());
        } finally {
            result.put("STATUS", status);
            result.put("msg", msg);
            return result.toJSONString();
        }
    }

    /**
     * 采购申请记录修改更新
     *
     * @param purchase
     * @return
     */
    @CrossOrigin
    @RequestMapping(value = "/Purchase/update", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String updatePurchase(@RequestBody Purchase purchase) {
        // 将获取的json数据封装一层，然后在给返回
        JSONObject result = new JSONObject();
        String status = "ERROR";
        String msg = "更新失败";
        int temp = 0;
        try {
            //更新操作
            //当进行采购申请修改操作时，
            // 点击提交：审批记录插入数据库，
            // 点击保存：审批记录不插入数据库
            //采购申请单修改前的两种状态：
            // 1、审核驳回，已驳回状态，再次修改。
            // 2、创建后未提交，草稿状态，再次修改。

            // 获取采购申请单的当前状态
            String applystate = purchase.getApplystate();
            //获取采购申请单的是否提交过的状态，从没提交过为0，提交过为1
            String executestate = purchase.getExecutestate();

            //如果进行采购申请单的修改操作，点击了提交，状态变成了审核中
            //这时需要插入到审批记录中，如果点击了保存，则不进行插入
            if (applystate.equals("审核中")) {

                //采购申请修改提交，审批记录插入数据库
                PurchaseRecord record = setPRecord(purchase, "提交");
                int c2 = purchaseRcdService.savePurchaseRecord(record);
                //System.out.println(c2);
                //如果采购申请原状态为草稿，第一次提交，则，提交状态设为1
                if (executestate.equals("0")) {
                    purchase.setExecutestate("1");
                }
                temp += c2;
            } else {
                temp += 1;
            }
            //更新采购申请单信息
            int c1 = purchaseService.updatePurchase(purchase);
            //System.out.println(c1);
            if (temp + c1 == 2) {
                status = "OK";
                msg = "更新成功";
                //return result.toJSONString();
            }
        } catch (Exception e) {
            msg = e.getMessage();
            System.out.println(e.getMessage());
        } finally {
            result.put("STATUS", status);
            result.put("msg", msg);
            return result.toJSONString();
        }
    }

    /**
     * 设置采购申请单的审批记录，功能函数，
     * 用于采购申请单【创建】和【修改】的时候使用
     *
     * @param purchase
     * @param opt
     * @return
     */
    private PurchaseRecord setPRecord(Purchase purchase, String opt) {
        PurchaseRecord record = new PurchaseRecord();
        record.setPurchapplyid(purchase.getPurchapplyid());
        record.setOpt_name(purchase.getOperuser());
        record.setOpt_departname(purchase.getOperdepartname());
        record.setOpt(opt);
        record.setRemark("");
        record.setOpt_date(purchase.getWritedate());
        return record;
    }

    /**
     * 查询所有采购申请 【待审核 】状态的记录，分页展示
     *
     * @param request
     * @return
     */
    @CrossOrigin
    @RequestMapping(value = "/Purchase/findAllOne", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String findAllPurchase(@RequestBody JSONObject request) {
        //创建采购申请条件查询对象
        PurchaseQuery purchaseQuery = new PurchaseQuery();

        //设置查询对象的【审核中】状态，查询所有处于此状态的申请单
        purchaseQuery.setApplystate("审核中");
        //设置分页查询的页码，每一页的数据条数
        purchaseQuery.setPage(request.getInteger("pageNum"));
        purchaseQuery.setRows(request.getInteger("pageSize"));

        return toJsonResult(purchaseQuery);
    }

    /**
     * 查询所有的采购申请记录
     *
     * @param request
     * @return
     */
    @CrossOrigin
    @RequestMapping(value = "/Purchase/findAllLimit", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String findAllPurchaseL(@RequestBody JSONObject request) {
        //获取前端传送过来的数据，searchForm：按条件搜索的表单数据
        //table_page：pageNum分页查询的页码，pageSize每一页的数据条数
        JSONObject searchForm = request.getJSONObject("searchForm");
        JSONObject table_page = request.getJSONObject("table_page");
        //新建查询对象
        PurchaseQuery purchaseQuery = new PurchaseQuery();
        if (!searchForm.isEmpty()) {

            String purchapplyid = searchForm.getString("purchapplyid");
            String createuser = searchForm.getString("createuser");
            String applystate = searchForm.getString("applystate");
            //如果查询表单中的：单据编号，不为空，则设置到查询对象中
            if (!purchapplyid.isEmpty()) {
                purchaseQuery.setPurchapplyid(purchapplyid);
            }
            //如果查询表单中的：申请人，不为空，则设置到查询对象中
            if (!createuser.isEmpty()) {
                purchaseQuery.setCreateuser(createuser);
            }
            //如果查询表单中的：申请单状态，不为空，则设置到查询对象中
            if (!applystate.isEmpty()) {
                purchaseQuery.setApplystate(applystate);
            }
        }

        Integer pageNum = table_page.getInteger("pageNum");
        Integer pageSize = table_page.getInteger("pageSize");

        //查询对象设置分页查询，页码，大小
        purchaseQuery.setPage(pageNum);
        purchaseQuery.setRows(pageSize);

        return toJsonResult(purchaseQuery);

    }

    /**
     *功能函数：用于查询采购申请单的记录有多个，需要分页展示，需要
     * 返回多个数据到前台时使用
     * 作用：多个不同数据整合为一个json数据字符串返回
     * 采购申请按条件查询返回，分页展示，返回一个json字符串
     */
    private String toJsonResult(PurchaseQuery purchaseQuery) {
        //查询符合条件的所有申请单记录
        List<Purchase> purchaseList = purchaseService.findAllLimit(purchaseQuery);
        //List<Purchase> purchaseList = purchaseService.findAll(purchaseQuery);
        //查询符合条件的记录的总条数
        int count = purchaseService.findAllCountLimit(purchaseQuery);
        JSONObject result = new JSONObject();
        result.put("table_data", purchaseList);
        result.put("pageTotal", count);
        return result.toJSONString();
    }

    /**
     * 通过采购申请id查询相应记录
     *
     * @param request
     * @return
     */
    @CrossOrigin
    @RequestMapping(value = "/Purchase/findById", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Purchase findPurchaseById(@RequestBody JSONObject request) {
        Purchase purchase = purchaseService.findById(request.getString("purchapplyid"));
        return purchase;
    }

    /**
     * 通过id查询采购申请记录和审批记录
     *
     * @param request
     * @return
     */
    @CrossOrigin
    @RequestMapping(value = "/Purchase/findAllById", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String findPurchRcdAllById(@RequestBody JSONObject request) {

        JSONObject table_page = request.getJSONObject("table_page");
        String purchapplyid = request.getString("purchapplyid");
        Integer pageNum = table_page.getInteger("pageNum");
        Integer pageSize = table_page.getInteger("pageSize");

        Purchase purchase = purchaseService.findById(purchapplyid);

        JSONObject result = getRcdAndCount(purchapplyid, pageNum, pageSize);
        result.put("purchase_data", purchase);
        return result.toJSONString();
    }

    /**
     * 通过id查询所有的审批记录
     *
     * @param request
     * @return
     */
    @CrossOrigin
    @RequestMapping(value = "/Purchase/findAllRcdById", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String findAllRecordById(@RequestBody JSONObject request) {
        JSONObject table_page = request.getJSONObject("table_page");
        String purchapplyid = request.getString("purchapplyid");
        Integer pageNum = table_page.getInteger("pageNum");
        Integer pageSize = table_page.getInteger("pageSize");
        JSONObject result = getRcdAndCount(purchapplyid, pageNum, pageSize);
        //System.out.println(result.toJSONString());
        return result.toJSONString();
    }

    /**
     * 功能函数：在需要查询相应条件下的所有审批记录时使用
     * 返回带有审批记录和记录总数的json对象
     * @param purchapplyid
     * @param pageNum
     * @param pageSize
     * @return
     */
    //通过id查找所有的审批记录，分页展示，需要记录总数，返回一个JSONObject类型的对象
    private JSONObject getRcdAndCount(String purchapplyid, Integer pageNum, Integer pageSize) {
        PurchaseRecord record = new PurchaseRecord();
        record.setPurchapplyid(purchapplyid);
        record.setPage(pageNum);
        record.setRows(pageSize);
        List<PurchaseRecord> purchaseRecords = purchaseRcdService.findAllLimit(record);
        int count = purchaseRcdService.findAllCount(record);
        JSONObject result = new JSONObject();
        result.put("record_data", purchaseRecords);
        result.put("pageTotal", count);
        return result;
    }

    /**
     * 采购申请审核、审批记录添加操作
     *
     * @param record
     * @return
     */
    @CrossOrigin
    @RequestMapping(value = "/Purchase/verify", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String verifyPurchaseAndRecord(@RequestBody PurchaseRecord record) {
        // 将获取的json数据封装一层，然后在给返回
        JSONObject result = new JSONObject();
        String status = "ERROR";
        String msg = "操作失败";
        try {
            //操作
            String purchapplyid = record.getPurchapplyid();
            String opt = record.getOpt();
            Purchase purchase = purchaseService.findById(purchapplyid);
            //如果审批审核通过，设置申请单的Executestate状态加 1 ，
            //当状态为 3 时，变为已发布 状态
            if (opt.equals("审核")) {

                String s = purchase.getExecutestate();
                int n = Integer.parseInt(s) + 1;
                if (n == 3) {
                    purchase.setApplystate("已发布");
                }
                purchase.setExecutestate(String.valueOf(n));

            } else {
                purchase.setApplystate("已驳回");
            }
            int c1 = purchaseService.updatePurchase(purchase);
            int c2 = purchaseRcdService.savePurchaseRecord(record);
            if (c1 + c2 == 2) {
                status = "OK";
                msg = "操作成功";
                //return result.toJSONString();
            }
        } catch (Exception e) {
            msg = e.getMessage();
            System.out.println(e.getMessage());
        } finally {
            result.put("STATUS", status);
            result.put("msg", msg);
            return result.toJSONString();
        }
    }
}
